package a11_单调栈;

import java.util.Stack;

/**
 * <p>
 * a04_接雨水复习3
 * </p>
 *
 * @author flyduck
 * @since 2025/4/8
 */
public class a04_接雨水复习3 {
    public int trap(int[] height) {
        Stack<Integer> stack = new Stack<>();
        stack.add(0);

        int totalArea = 0;
        for (int i = 1; i < height.length; i++) {
            while (!stack.isEmpty() && height[stack.peek()] < height[i]){
                Integer pop = stack.pop();
                if(!stack.isEmpty()){
                    int h = Math.min(height[i],height[stack.peek()]) - height[pop];
                    int w = i - stack.peek() - 1;
                    totalArea += h * w;
                }
            }
            stack.add(i);
        }
        return totalArea;
    }
}
